<template>
  <div class="app-container" v-if="!isExport">
    <el-form ref="queryForm" :model="queryParams" inline>
      <el-form-item prop="scaleId">
        <el-select
          v-model="queryParams.scaleId"
          placeholder="---量表名称---"
          clearable=""
        >
          <el-option
            :label="item.scaleTitle"
            :value="item.scaleId"
            v-for="item in allSurvey"
            :key="item.scaleId"
            @keyup.enter.native="handleQuery"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="departId">
        <el-select
          v-model="queryParams.departId"
          placeholder="部门名称"
          clearable=""
        >
          <el-option
            :label="item.deptName"
            :value="item.deptId"
            v-for="item in allDept"
            :key="item.deptId"
            @keyup.enter.native="handleQuery"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item prop="time">
        <el-date-picker
          v-model="queryParams.time"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :format="'yyyy-MM-dd'"
          @keyup.enter.native="handleQuery"
        >
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-date-picker
          v-model="queryParams.startTime"
          type="datetime"
          placeholder="开始日期"
          :format="'yyyy-MM-dd'"
          @keyup.enter.native="handleQuery"
          clearable
        >
        </el-date-picker>
        <el-date-picker
          v-model="queryParams.endTime"
          type="datetime"
          placeholder="结束日期"
          :format="'yyyy-MM-dd'"
          @keyup.enter.native="handleQuery"
          clearable
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="sex">
        <el-select
          v-model="queryParams.sex"
          placeholder="性别"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <el-option label="男" value="0"></el-option>
          <el-option label="女" value="1"></el-option>
          <el-option label="未知" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button type="warning" icon="el-icon-refresh" @click="handleReset">
          重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-tabs v-model="activeName" type="border-card" class="el-tabs">
      <el-tab-pane label="个体报告" name="indReport">
        <el-row :gutter="10">
          <el-col :span="10">
            <el-table
              ref="loginFormRef"
              :data="loginTable"
              v-loading="loading"
              tooltip-effect="dark"
              style="width: 100%"
              border
              stripe
              :header-cell-style="{
                'text-align': 'center',
                background: '#2196f3',
                color: '#fff',
              }"
              :cell-style="{ 'text-align': 'center' }"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column type="index" width="50" label="序号">
              </el-table-column>
              <el-table-column prop="loginName" label="登录名" width="100">
              </el-table-column>
              <el-table-column prop="userName" label="姓名" width="100">
              </el-table-column>
              <el-table-column prop="sex" label="性别" width="50">
                <template slot-scope="scope">
                  <span v-if="scope.row.sex === '1'">女</span>
                  <span v-else-if="scope.row.sex === '0'">男</span></template
                >
              </el-table-column>
              <el-table-column prop="createTime" label="提交时间">
              </el-table-column>
            </el-table>

            <pagination
              v-show="total > 0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getAllList"
            />
            <div class="text">
              注: 为了保障系统的正常运行，建议您一次统计分析数量不超过2000人。
            </div>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-button type="primary" icon="el-icon-search" @click="openDialog"
              >组合</el-button
            >
          </el-col>
          <el-col :span="10">
            <el-table
              ref="combFormRef"
              :data="combTable"
              tooltip-effect="dark"
              style="width: 100%"
              border
              stripe
              :header-cell-style="{
                'text-align': 'center',
                background: '#2196f3',
                color: '#fff',
              }"
              :cell-style="{ 'text-align': 'center' }"
            >
              <el-table-column prop="combinationName" label="名称">
              </el-table-column>
              <el-table-column label="操作" width="70">
                <template slot-scope="scope">
                  <el-link
                    type="primary"
                    :underline="false"
                    @click="del(scope.row.combinationId)"
                    >[删除]</el-link
                  >
                </template>
              </el-table-column>
            </el-table>
            <div class="btn">
              <el-button
                type="danger"
                icon="el-icon-delete"
                plain
                size="mini"
                @click="delAll()"
                >清空</el-button
              >
              <el-button
                type="success"
                icon="el-icon-s-order"
                plain
                size="mini"
                @click="statistics()"
                >统计</el-button
              >
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
      <!-- <el-tab-pane label="团队报告" name="teamReport"> </el-tab-pane> -->
    </el-tabs>

    <el-dialog :visible.sync="dialogFormVisible" width="30%">
      <span>
        <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogRule">
          <el-form-item prop="name">
            <el-input
              v-model="dialogForm.name"
              placeholder="输入组合名称"
            ></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="out()">取 消</el-button>
        <el-button type="primary" @click="submitForm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>

  <div class="app-container" v-else>
    <Export :exportData="exportData" @cancel="cancel"></Export>
  </div>
</template>

<script>
import Export from "./export.vue";
import {
  listStatAnalysis,
  addCombination,
  delCombination,
  cleanCombination,
  getStatAnalysis,
  listAllSurvey,
  listAllDept,
  listCombination,
} from "@/api/consult/stat-analysis.js";
export default {
  // name: "统计分析",
  data() {
    return {
      loading: false,
      ids: [],
      // 非单个禁用
      single: true,
      // 组合弹框
      dialogFormVisible: false,
      queryParams: {
        // scaleId: null, //量表名称
        // departId: null, //部门名称
        // time: null,
        // sex: null,
        // beginTime: null,
        // endTime: null,
        // pageNum: 1,
        // pageSize: 10,
        // riskLevel: 10,
        pageNum: 1,
        pageSize: 10,
        scaleId: null,
        scaleTitle: null,
        resultId: null,
        loginName: null,
        userName: null,
        countScore: null,
        factorScore: null,
        resultContent: null,
        factorResult: null,
        userAnswer: null,
        classesName: null,
        departId: null,
        createTime: null,
        startTime: null,
        endTime: null,
        riskLevel: 10,
      },
      allSurvey: [],
      allDept: [],
      activeName: "indReport",
      // 登录表格
      loginTable: [],
      multipleSelection: [],
      total: 0,
      form: {},
      // 组合表格
      combTable: [],
      newScaleId: null,
      // 弹框
      dialogForm: {
        name: null,
      },
      dialogRule: {
        name: [{ required: true, message: "请输入组合名称", trigger: "blur" }],
      },
      // 是否为导出页面
      isExport: false,
      exportData: [
        // {
        //   title: "日常生活能力评定量表(14题)统计报告",
        //   time: "2021-11-11",
        //   DescriptTable: [
        //     {
        //       team: "组合1",
        //       dimension: "总评",
        //       average: "33.67",
        //       Standard: "5.67",
        //     },
        //   ],
        //   differTable: [
        //     {
        //       dimName: "总评",
        //       differ: "组间变异",
        //       squares: "0.00",
        //       freedom: "0",
        //       average: "0.00",
        //       F_data: "0.00",
        //       P_data: "P>0.05",
        //     },
        //     {
        //       dimName: "总评",
        //       differ: "组内变异",
        //       squares: "12.00",
        //       freedom: "0",
        //       average: "0.00",
        //       F_data: "0.00",
        //       P_data: "P>0.05",
        //     },
        //     {
        //       dimName: "总评",
        //       differ: "总变异",
        //       squares: "23.00",
        //       freedom: "0",
        //       average: "0.00",
        //       F_data: "0.00",
        //       P_data: "P>0.05",
        //     },
        //   ],
        //   conclusion: "各团体间在总评上得分差异不显著(F=0.00,P>0.05)",
        // },
      ],
    };
  },
  created() {
    this.getAllSurvey(); //获取所有量表
    this.getAllDept(); //获取所有部门
  },
  components: {
    Export,
  },
  methods: {
    // 获取所有量表
    getAllSurvey() {
      listAllSurvey().then((res) => {
        this.allSurvey = res.data;
        // console.log("量表", this.allSurvey);
      });
    },
    getAllDept() {
      listAllDept().then((res) => {
        this.allDept = res.data;
        // console.log("部门",  this.allDept);
      });
    },
    // 转换数据格式
    formatJson(time) {
      const date = new Date(time);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const formateTime = `${year}-${month}-${day}`;
      return formateTime;
    },
    // 搜索
    handleQuery() {
      if (this.queryParams.scaleId == null) {
        this.$message({
          message: "请选择量表",
          type: "warning",
        });
        return false;
      } else {
        this.loading = true;
        const time = this.queryParams.startTime && this.queryParams.endTime;
        if (time) {
       
          this.queryParams.beginTime = this.formatJson(
            this.queryParams.startTime
          );
          this.queryParams.endTime = this.formatJson(this.queryParams.endTime);
        }

     
        this.queryParams.pageNum = 1;
        this.getAllList();
        this.getAllcombination(this.queryParams.scaleId);
        this.loading = false;
      }
    },
    // 获取个体报告数据
    getAllList() {
      console.log("数据", this.queryParams);
      listStatAnalysis(this.queryParams).then((res) => {
        
        if (res.code == 200) {
          this.loginTable = res.rows;
          this.total = res.total;
        }
      });
    },
    // 重置
    reset() {
      this.queryParams = {
        scaleTitle: null, //量表名称
        departName: null, //部门名称
        time: null,
        sex: null,
      };
    },
    handleReset() {
      this.queryParams.pageNum = 1;
      this.reset();
      this.getAllList();
      this.combTable = [];
      
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log("multipleSelection", this.multipleSelection);
    },

    openDialog() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请选择需要组合的数据",
          type: "warning",
        });
      } else {
        this.dialogFormVisible = true;
      }
    },
    // 取消提交
    out() {
      this.dialogFormVisible = false;
      this.$refs.dialogFormRef.resetFields();
    },
    // 提交组合弹框表单
    submitForm() {
      this.$refs.dialogFormRef.validate((valid) => {
        if (valid) {
          console.log(this.multipleSelection);
          const resultIds = this.multipleSelection.map((item) => {
            return item.resultId;
          });
          const subData = {
            combinationName: this.dialogForm.name,
            resultIds: resultIds,
            scaleId: this.multipleSelection[0].scaleId,
          };
          addCombination(subData).then((res) => {
            // console.log("addCombination", res);
            if (res.code === 200) {
              this.newScaleId = res["data"].scaleId;

              this.getAllcombination(this.newScaleId);
              this.$message({
                message: "组合成功",
                type: "success",
              });
            }
          });

          this.out();
        } else {
          return false;
        }
      });
    },

    // 获取所有组合
    getAllcombination(id) {
      listCombination(id).then((res) => {
        // console.log("allList", res);
        this.combTable = res.data;
      });
    },
    del(id) {
      delCombination(id).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: "删除成功",
            type: "success",
          });

          if (this.newScaleId == null) {
            this.getAllcombination(this.queryParams.scaleId);
          } else {
            this.getAllcombination(this.newScaleId);
          }
        }
      });
    },
    // 清空
    delAll() {
      if (!this.queryParams.scaleId) {
        return false;
      } else {
        cleanCombination(this.queryParams.scaleId).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.getAllcombination(this.queryParams.scaleId);
          }
        });
      }
    },
    // 统计
    statistics() {
      if (this.combTable.length == 0) {
        this.$message({
          message: "请先组合",
          type: "warning",
        });
      } else {
        this.isExport = true;
        getStatAnalysis(this.queryParams.scaleId).then((res) => {
          if (res.code == 200) {
            this.exportData = res.data;
          // console.log("exportData", this.exportData);
          }
        });
      }
    },
    // 取消
    cancel() {
      this.isExport = false;
    },
  },
};
</script>

<style scoped>
.app-container {
  min-height: 100vh;
}
.el-tabs {
  min-height: 80vh;
}
.text {
  font-size: 0.8rem;
  text-align: center;
  margin: 1.5rem 0;
}
.btn {
  margin: 1.5rem 0;
  text-align: end;
}
</style>